<template>
  <el-select
    v-model="selectedCourseId"    
    clearable
    filterable
    remote
    reserve-keyword
    placeholder="请选择课程"
    :remote-method="remoteSearch"
    :loading="loading"
    size="small"
    @change="handleChange"
    :style="{ width: selectWidth }"
  >
    <el-option
      v-for="item in courseList"
      :key="item.id"
      :label="item.courseName"
      :value="item.id">
    </el-option>
  </el-select>
</template>

<script>
import api from '@/common/api'

export default {
  name: 'CourseSelect',
  props: {
    value: {
      type: [Number, String],
      default: null
    },
    widthFixed: {
      type: Boolean,
      default: false
    },
    initSelectFirst: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      courseList: [],
      loading: false,
      selectedCourseId: this.value,      
    }
  },
  watch: {
    value(newVal) {
      this.selectedCourseId = newVal
      if (newVal && !this.courseList.find(course => course.id === newVal)) {
        this.loadSelectedCourse(newVal)
      }
    }
  },
  computed: {
    selectWidth() {
      if (this.widthFixed) return 'auto'
      return this.selectedCourseId ? '200px' : '120px'
    }
  },
  created() {
    this.remoteSearch('')
    if (this.value) {
      this.loadSelectedCourse(this.value)
    }
  },
  methods: {
    async loadSelectedCourse(courseId) {
      try {
        const { data } = await api.admin_getCourseList({
          currentPage: 1,
          limit: 1,
          keyword: '',
          courseId: courseId
        })
        if (data.data.records.length > 0) {
          const selectedCourse = data.data.records[0]
          if (!this.courseList.find(course => course.id === selectedCourse.id)) {
            this.courseList.push(selectedCourse)
          }
        }
      } catch (error) {
        this.$message.error('获取课程信息失败')
      }
    },
    async remoteSearch(query) {
      this.loading = true
      try {
        const { data } = await api.admin_getCourseList({
          currentPage: 1,
          limit: 50,
          keyword: query
        })
        this.courseList = data.data.records
        
        if (this.initSelectFirst && !this.value && this.courseList.length) {
          this.selectedCourseId = this.courseList[0].id
          this.handleChange(this.selectedCourseId)
        }
      } catch (error) {
        this.$message.error('搜索课程失败')
      } finally {
        this.loading = false
      }
    },
    handleChange(val) {
      this.$emit('input', val)
      this.$emit('change', val)      
    }
  }
}
</script>

<style scoped>
.el-select {
  display: inline-block;
  transition: width 0.3s;
}

/* Only apply hover effect when not width-fixed */
.el-select:not([style*="width: auto"]):hover,
.el-select:not([style*="width: auto"]):has(.is-focus) {
  width: 200px !important;
}
</style>
